<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()"
             label-width="80px">
      <el-form-item label="分类" prop="foodTypeId">
        <el-select v-model="dataForm.foodTypeId" filterable placeholder="请选择">
          <el-option
            v-for="item in foodTypeList"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="菜品名称" prop="foodName">
        <el-input v-model="dataForm.foodName" placeholder="菜品名称"></el-input>
      </el-form-item>
      <el-form-item label="菜品简介" prop="introduce">
        <el-input type="textarea" :rows="5" v-model="dataForm.introduce" placeholder="菜品简介"></el-input>
      </el-form-item>
      <el-form-item label="价格" prop="price">
        <el-input-number v-model="dataForm.price" :precision="2" :step="1"></el-input-number>
      </el-form-item>
      <el-form-item label="图片" prop="photo">
        <!--<el-input v-model="dataForm.photo" placeholder="图片"></el-input>-->
        <el-upload
          ref="upload"
          class="avatar-uploader"
          :action="url"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload">
          <img v-if="imageUrl" :src="imageUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="库存" prop="repertory">
        <el-input-number v-model="dataForm.repertory"></el-input-number>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 250px;
    height: 180px;
    line-height: 180px;
    text-align: center;
  }
  .avatar {
    width: 250px;
    height: 180px;
    display: block;
  }
</style>

<script>
  export default {
    data () {
      return {
        visible: false,
        url: '',
        dataForm: {
          id: 0,
          foodTypeId: '',
          foodName: '',
          introduce: '',
          price: '',
          photo: '',
          repertory: ''
        },
        imageUrl: '',
        foodTypeList: [],
        dataRule: {
          foodTypeId: [
            {required: true, message: '分类不能为空', trigger: 'blur'}
          ],
          foodName: [
            {required: true, message: '菜品名称不能为空', trigger: 'blur'}
          ],
          introduce: [
            {required: true, message: '菜品简介不能为空', trigger: 'blur'}
          ],
          price: [
            {required: true, message: '价格不能为空', trigger: 'blur'}
          ],
          repertory: [
            {required: true, message: '库存不能为空', trigger: 'blur'}
          ]
        }
      }
    },
    created () {
      this.initFootType()
    },
    methods: {
      handleAvatarSuccess (res, file) {
        this.imageUrl = URL.createObjectURL(file.raw)
        this.dataForm.photo = res.id
      },
      beforeAvatarUpload (file) {
        const isJPG = file.type === 'image/jpeg'
        const isLt10M = file.size / 1024 / 1024 < 10

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!')
        }
        if (!isLt10M) {
          this.$message.error('上传头像图片大小不能超过 10MB!')
        }
        return isJPG && isLt10M
      },
      init (id) {
        this.dataForm.id = id || 0
        this.url = this.$http.adornUrl(`/sys/oss/upload?token=${this.$cookie.get('token')}`)
        this.imageUrl = ''
        this.visible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl(`/dcxt/food/info/${this.dataForm.id}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.dataForm.foodTypeId = data.food.foodTypeId
                this.dataForm.foodName = data.food.foodName
                this.dataForm.introduce = data.food.introduce
                this.dataForm.price = data.food.price
                this.dataForm.photo = data.food.photo
                this.dataForm.repertory = data.food.repertory
                if (data.food.photoUrl != null) {
                  this.imageUrl = this.$http.adornUrl(`/upload/${data.food.photoUrl}?token=${this.$cookie.get('token')}`)
                }
              }
            })
          }
        })
      },
      initFootType () {
        this.$http({
          url: this.$http.adornUrl(`/dcxt/foottype/list`),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.foodTypeList = data.data
          }
        })
      },
      handleSuccess (response, file, fileList) {
        this.dataForm.photo = response.id
      },
      // 表单提交
      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl(`/dcxt/food/${!this.dataForm.id ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                'id': this.dataForm.id || undefined,
                'foodTypeId': this.dataForm.foodTypeId,
                'foodName': this.dataForm.foodName,
                'introduce': this.dataForm.introduce,
                'price': this.dataForm.price,
                'photo': this.dataForm.photo,
                'repertory': this.dataForm.repertory
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      }
    }
  }
</script>
